<?php

namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Curl;
use app\common\lib\Num;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\lib\Time;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;

class SystemConfig
{

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\SystemConfig();
    }

    public function get($key)
    {
        return $this->model->where('key',$key)->value('value');
    }

    public function getListByKeys($keys){
        if (empty($keys)){
            return [];
        }

        $map = [
            ['key','in',$keys],
            ['is_use','=',1]
        ];
        $data = $this->model->getNormalListByWhere($map);
        if (!$data) {
            return [];
        }
        $data=$data->toArray();
        return $data;
    }

    public function getResetInfo($list){
        $result = [
            'commission_rate'=>0,
            'earnest_rate'=>0,
        ];
        if (empty($list)){
            return $result;
        }

        foreach ($list as $k=>$v){
            $v['key'] == 'commission_rate' && $result['commission_rate'] = $v['value'];
            $v['key'] == 'earnest_rate' && $result['earnest_rate'] = $v['value'];
        }
        return $result;
    }

    public function save($data){
        if(empty($data)){
            throw new Exception('数据不存在');
        }

        $list = $this->getListByKeys(array_keys($data));
        if (empty($list)){
            throw new Exception('数据不存在');
        }

        $saveData = [];
        foreach ($list as $k=>$v){
            foreach ($data as $k1=>$v1){
                if ($v['key'] == $k1){
                    $saveData[$k]['id'] = $v['id'];
                    $saveData[$k]['value'] = $v1;
                }
            }
        }
        if (empty($saveData)){
            throw new Exception('数据异常，更新失败');
        }

        $res = $this->model->saveAll($saveData);
        return $res;
    }
}
